<template>
  <div class="consulting-management">
    <div class="search-section">
      <el-card>
        <el-form :model="searchForm" inline>
          <el-form-item label="关键词">
            <el-input v-model="searchForm.keyWords" placeholder="姓名关键词" clearable />
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select v-model="searchForm.status" clearable placeholder="请选择">
              <el-option label="全部" :value="''" />
              <el-option label="审核通过" :value="1" />
              <el-option label="待审核" :value="0" />
              <el-option label="审核未通过" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="擅长领域">
            <el-input v-model="searchForm.specialization" placeholder="如：婚姻家庭" clearable />
          </el-form-item>
          <el-form-item label="咨询模式">
            <el-select v-model="searchForm.consultationMode" clearable placeholder="请选择">
              <el-option label="线上" value="ONLINE" />
              <el-option label="线下" value="OFFLINE" />
              <el-option label="线上+线下" value="HYBRID" />
            </el-select>
          </el-form-item>
          <el-form-item label="价格区间">
            <el-input v-model="searchForm.minPrice" placeholder="最低" style="width: 100px" />
            <span style="margin: 0 6px;">~</span>
            <el-input v-model="searchForm.maxPrice" placeholder="最高" style="width: 100px" />
          </el-form-item>
          <el-form-item label="城市">
            <el-input v-model="searchForm.serviceArea" placeholder="所在城市" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <div class="list-section">
      <el-card>
        <div slot="header">
          <span>咨询师列表</span>
        </div>

        <el-table v-loading="loading" :data="list" style="width: 100%">
          <el-table-column prop="realName" label="姓名" width="140" show-overflow-tooltip />
          <el-table-column prop="avatarUrl" label="头像" width="140">
            <template slot-scope="scope">
              <el-avatar :src="scope.row.avatarUrl" :size="56" />
            </template>
          </el-table-column>
          <el-table-column prop="specialization" label="擅长领域" width="220">
            <template slot-scope="scope">
              <el-tag v-for="sp in (scope.row.specialization || [])" :key="sp" size="mini" style="margin-right: 4px; margin-bottom: 2px;">{{ sp }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="yearsOfExperience" label="年限" width="70" align="center" />
          <el-table-column prop="hourlyRate" label="价格(元/时)" width="100" align="center" />
          <el-table-column prop="consultationMode" label="模式" width="100" align="center" />
          <el-table-column prop="averageRating" label="评分" width="80" align="center" />
          <el-table-column prop="completedSessions" label="完成数" width="90" align="center" />
          <el-table-column prop="serviceAreas" label="服务区域" width="220">
            <template slot-scope="scope">
              <el-tag v-for="area in (scope.row.serviceAreas || [])" :key="area" size="mini" style="margin-right: 4px; margin-bottom: 2px;">{{ area }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="workingHours" label="工作时间" width="140" />
          <el-table-column prop="counselorStatus" label="审核状态" width="100" align="center">
            <template slot-scope="scope">
              <el-tag :type="getStatusTag(scope.row.counselorStatus)">{{ getStatusLabel(scope.row.counselorStatus) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createAt" label="创建时间" width="160" show-overflow-tooltip />
          <el-table-column label="操作" width="280" fixed="right" align="center">
            <template slot-scope="scope">
              <div class="action-buttons-row">
                <el-button size="mini" type="primary" @click="viewCounselorDetail(scope.row)">查看详情</el-button>
                <el-button size="mini" type="success" @click="openReviewDialog(scope.row, 1)" :disabled="scope.row.counselorStatus === 1">审核通过</el-button>
                <el-button size="mini" type="warning" @click="openReviewDialog(scope.row, 2)" :disabled="scope.row.counselorStatus === 2">审核不通过</el-button>
                <el-button size="mini" type="danger" @click="openReviewDialog(scope.row, 3)" :disabled="scope.row.counselorStatus === 3">封禁</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            :current-page="searchForm.page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="searchForm.pageSize"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 咨询师详情对话框 -->
    <el-dialog :visible.sync="detailVisible" title="咨询师详情" width="70%" :close-on-click-modal="false">
      <div v-loading="detailLoading" v-if="counselorDetail" class="counselor-detail">
        <div class="detail-header">
          <div class="avatar-section">
            <el-avatar :src="counselorDetail.avatarUrl" :size="100" />
          </div>
          <div class="basic-info">
            <h2>{{ counselorDetail.realName }}</h2>
            <div class="info-row">
              <span class="info-label">用户ID：</span>
              <span class="info-value">{{ counselorDetail.userId }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">UID：</span>
              <span class="info-value">{{ counselorDetail.uid }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">邮箱：</span>
              <span class="info-value">{{ counselorDetail.email }}</span>
            </div>
          </div>
        </div>

        <el-divider />

        <div class="detail-content">
          <div class="info-grid">
            <div class="info-item">
              <span class="info-label">性别：</span>
              <span class="info-value">{{ counselorDetail.gender === 'M' ? '男' : counselorDetail.gender === 'F' ? '女' : '未知' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">年龄：</span>
              <span class="info-value">{{ counselorDetail.age || '未填写' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">联系电话：</span>
              <span class="info-value">{{ counselorDetail.contactPhone || '未填写' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">咨询状态：</span>
              <el-tag :type="getStatusTag(counselorDetail.counselorStatus)">{{ getStatusLabel(counselorDetail.counselorStatus) }}</el-tag>
            </div>
            <div class="info-item">
              <span class="info-label">系统状态：</span>
              <el-tag :type="counselorDetail.status === '1' ? 'success' : 'danger'">{{ counselorDetail.status === '1' ? '正常' : '禁用' }}</el-tag>
            </div>
            <div class="info-item">
              <span class="info-label">组织ID：</span>
              <span class="info-value">{{ counselorDetail.orgId || '无' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">从业年限：</span>
              <span class="info-value">{{ counselorDetail.yearsOfExperience || 0 }} 年</span>
            </div>
            <div class="info-item">
              <span class="info-label">时薪：</span>
              <span class="info-value">{{ counselorDetail.hourlyRate || 0 }} 元/时</span>
            </div>
            <div class="info-item">
              <span class="info-label">咨询模式：</span>
              <span class="info-value">{{ counselorDetail.consultationMode || '未填写' }}</span>
            </div>
            <div class="info-item" style="grid-column: 1 / -1;">
              <span class="info-label">平均评分：</span>
              <span class="info-value" style="display: flex; align-items: center;">
                <el-rate :value="parseFloat(counselorDetail.averageRating) || 0" disabled :max="5" />
                <span style="margin-left: 8px;">{{ counselorDetail.averageRating || 0 }} 分</span>
              </span>
            </div>
            <div class="info-item">
              <span class="info-label">已完成咨询：</span>
              <span class="info-value">{{ counselorDetail.completedSessions || 0 }} 次</span>
            </div>
            <div class="info-item">
              <span class="info-label">工作时间：</span>
              <span class="info-value">{{ counselorDetail.workingHours || '未填写' }}</span>
            </div>
          </div>

          <div class="info-section">
            <h3>擅长领域</h3>
            <div class="tags-container">
              <el-tag v-for="sp in (counselorDetail.specialization || [])" :key="sp" size="small" style="margin-right: 8px; margin-bottom: 8px;">{{ sp }}</el-tag>
              <span v-if="!counselorDetail.specialization || counselorDetail.specialization.length === 0" class="empty-text">未填写</span>
            </div>
          </div>

          <div class="info-section">
            <h3>服务区域</h3>
            <div class="tags-container">
              <el-tag v-for="area in (counselorDetail.serviceAreas || [])" :key="area" size="small" type="success" style="margin-right: 8px; margin-bottom: 8px;">{{ area }}</el-tag>
              <span v-if="!counselorDetail.serviceAreas || counselorDetail.serviceAreas.length === 0" class="empty-text">未填写</span>
            </div>
          </div>

          <div class="info-section">
            <h3>咨询风格</h3>
            <div class="tags-container">
              <el-tag v-for="style in (counselorDetail.enlightenStyle || [])" :key="style" size="small" type="info" style="margin-right: 8px; margin-bottom: 8px;">{{ style }}</el-tag>
              <span v-if="!counselorDetail.enlightenStyle || counselorDetail.enlightenStyle.length === 0" class="empty-text">未填写</span>
            </div>
          </div>

          <div class="info-section" v-if="counselorDetail.certifications && counselorDetail.certifications.length > 0">
            <h3>资质证书</h3>
            <div class="certifications-container">
              <el-image
                v-for="(cert, index) in counselorDetail.certifications"
                :key="index"
                :src="cert"
                fit="cover"
                style="width: 200px; height: 150px; margin-right: 12px; margin-bottom: 12px; border-radius: 4px;"
                :preview-src-list="counselorDetail.certifications"
              />
            </div>
          </div>

          <div class="info-section" v-if="counselorDetail.counselorIntroduction">
            <h3>个人简介</h3>
            <div class="introduction-text">{{ counselorDetail.counselorIntroduction }}</div>
          </div>

          <div class="info-section">
            <h3>时间信息</h3>
            <div class="info-grid">
              <div class="info-item">
                <span class="info-label">创建时间：</span>
                <span class="info-value">{{ counselorDetail.createAt || '未填写' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">更新时间：</span>
                <span class="info-value">{{ counselorDetail.updateAt || '未填写' }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 审核/封禁咨询师对话框 -->
    <el-dialog :visible.sync="reviewDialog.visible" :title="reviewDialog.title" width="500px">
      <el-form :model="reviewDialog.form" label-width="100px" :rules="reviewDialog.rules" ref="reviewForm">
        <el-form-item label="咨询师ID">
          <span>{{ reviewDialog.form.id }}</span>
        </el-form-item>
        <el-form-item label="咨询师姓名">
          <span>{{ reviewDialog.form.realName }}</span>
        </el-form-item>
        <el-form-item label="当前状态">
          <el-tag :type="getStatusTag(reviewDialog.form.currentStatus)">
            {{ getStatusLabel(reviewDialog.form.currentStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="操作类型">
          <el-tag :type="getActionTag(reviewDialog.form.status)">
            {{ getActionLabel(reviewDialog.form.status) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="审核信息" prop="reviewMessage">
          <el-input 
            type="textarea" 
            v-model="reviewDialog.form.reviewMessage" 
            :rows="4" 
            maxlength="200" 
            show-word-limit 
            placeholder="请输入审核备注" 
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reviewDialog.visible = false">取 消</el-button>
        <el-button type="primary" :loading="reviewDialog.submitting" @click="submitReview">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getConsultantPage, getCounselorDetail, checkCounselor } from '@/api/consulting'

export default {
  name: 'ConsultingManagement',
  data() {
    return {
      loading: false,
      list: [],
      total: 0,
      detailVisible: false,
      detailLoading: false,
      counselorDetail: null,
      reviewDialog: {
        visible: false,
        title: '审核咨询师',
        submitting: false,
        form: {
          id: '',
          realName: '',
          currentStatus: '',
          status: '',
          reviewMessage: ''
        },
        rules: {
          reviewMessage: [{ required: true, message: '请输入审核信息', trigger: 'blur' }]
        }
      },
      searchForm: {
        page: 1,
        pageSize: 10,
        status: '',
        specialization: '',
        consultationMode: '',
        minPrice: '',
        maxPrice: '',
        serviceArea: '',
        keyWords: ''
      }
    }
  },
  computed: {},
  mounted() {
    this.fetchList()
  },
  methods: {
    async fetchList() {
      this.loading = true
      try {
        const res = await getConsultantPage(this.searchForm)
        if (res?.code === 1) {
          const arr = Array.isArray(res?.data) ? res.data : (res?.data?.records || [])
          this.list = arr
          const totalFromMap = res?.map && (res.map.total ?? res.map.count ?? res.map.totalCount)
          const totalFromData = res?.data && (res.data.total ?? res.data.count ?? res.data.totalCount)
          const totalFromRoot = typeof res?.total === 'number' ? res.total : undefined
          const totalCandidate = totalFromMap ?? totalFromData ?? totalFromRoot
          if (typeof totalCandidate === 'number') {
            this.total = totalCandidate
          } else {
            const pageIndex = Number(this.searchForm.page) || 1
            const size = Number(this.searchForm.pageSize) || 10
            this.total = arr.length >= size ? (pageIndex + 1) * size : (pageIndex - 1) * size + arr.length
          }
        }
      } catch (e) {
        this.list = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.searchForm.page = 1
      this.fetchList()
    },
    handleReset() {
      this.searchForm = { page: 1, pageSize: 10, status: '', specialization: '', consultationMode: '', minPrice: '', maxPrice: '', serviceArea: '', keyWords: '' }
      this.fetchList()
    },
    handleCurrentChange(page) {
      this.searchForm.page = page
      this.fetchList()
    },
    handleSizeChange(size) {
      this.searchForm.pageSize = size
      this.searchForm.page = 1
      this.fetchList()
    },
    getStatusLabel(status) {
      const map = { 1: '审核通过', 0: '待审核', 2: '审核未通过', 3: '封禁' }
      return map[status] || '未知'
    },
    getStatusTag(status) {
      const map = { 1: 'success', 0: 'warning', 2: 'danger', 3: 'danger' }
      return map[status] || 'info'
    },
    getActionLabel(status) {
      const map = { 1: '审核通过', 2: '审核不通过', 3: '封禁' }
      return map[status] || '未知'
    },
    getActionTag(status) {
      const map = { 1: 'success', 2: 'warning', 3: 'danger' }
      return map[status] || 'info'
    },
    async viewCounselorDetail(row) {
      // 尝试从多个可能的字段获取 counselorUid
      const counselorUid = row.uid || row.counselorUid || row.id
      if (!counselorUid) {
        this.$message.warning('未找到咨询师ID')
        return
      }
      
      this.detailVisible = true
      this.detailLoading = true
      this.counselorDetail = null
      
      try {
        const res = await getCounselorDetail(counselorUid)
        if (res?.code === 1) {
          this.counselorDetail = res.data || null
        } else {
          this.$message.error(res?.msg || '获取咨询师详情失败')
          this.detailVisible = false
        }
      } catch (error) {
        console.error('获取咨询师详情失败:', error)
        this.$message.error('获取咨询师详情失败')
        this.detailVisible = false
      } finally {
        this.detailLoading = false
      }
    },
    openReviewDialog(row, status) {
      // status: 1-通过审核, 2-审核不通过, 3-封禁
      const statusLabels = { 1: '审核通过', 2: '审核不通过', 3: '封禁' }
      const counselorId = row.uid || row.counselorUid || row.id
      
      if (!counselorId) {
        this.$message.warning('未找到咨询师ID')
        return
      }
      
      this.reviewDialog = {
        visible: true,
        title: status === 3 ? '封禁咨询师' : '审核咨询师',
        submitting: false,
        form: {
          id: counselorId,
          realName: row.realName || '未知',
          currentStatus: row.counselorStatus || 0,
          status: status,
          reviewMessage: ''
        },
        rules: {
          reviewMessage: [{ required: true, message: '请输入审核信息', trigger: 'blur' }]
        }
      }
    },
    async submitReview() {
      this.$refs.reviewForm.validate(async (valid) => {
        if (!valid) return
        
        try {
          this.reviewDialog.submitting = true
          const payload = {
            id: this.reviewDialog.form.id,
            status: this.reviewDialog.form.status,
            reviewMessage: this.reviewDialog.form.reviewMessage
          }
          
          await checkCounselor(payload)
          const actionLabel = this.getActionLabel(this.reviewDialog.form.status)
          this.$message.success(`${actionLabel}成功`)
          this.reviewDialog.visible = false
          this.fetchList()
        } catch (error) {
          // 错误消息已由统一请求处理
        } finally {
          this.reviewDialog.submitting = false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.consulting-management { padding: 20px; }
.search-section { margin-bottom: 16px; }
.pagination-wrapper { margin-top: 16px; text-align: right; }

.action-buttons-row {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  grid-column-gap: 4px;
  grid-row-gap: 4px;
  > .el-button {
    min-width: auto;
    padding: 2px 4px;
    font-size: 11px;
    line-height: 1.2;
    width: 100%;
    box-sizing: border-box;
    min-height: 26px;
    align-self: stretch;
    margin-left: 0 !important;
    display: block;
  }
}

.counselor-detail {
  .detail-header {
    display: flex;
    align-items: flex-start;
    margin-bottom: 20px;
    
    .avatar-section {
      margin-right: 24px;
    }
    
    .basic-info {
      flex: 1;
      
      h2 {
        margin: 0 0 16px 0;
        color: #303133;
        font-size: 24px;
        font-weight: 600;
      }
      
      .info-row {
        margin-bottom: 8px;
        
        .info-label {
          font-weight: 600;
          color: #606266;
          margin-right: 8px;
          min-width: 80px;
          display: inline-block;
        }
        
        .info-value {
          color: #303133;
        }
      }
    }
  }
  
  .detail-content {
    .info-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 16px;
      margin-bottom: 24px;
      
      .info-item {
        display: flex;
        align-items: center;
        
        .info-label {
          font-weight: 600;
          color: #606266;
          margin-right: 8px;
          min-width: 100px;
        }
        
        .info-value {
          color: #303133;
          flex: 1;
        }
      }
    }
    
    .info-section {
      margin-bottom: 24px;
      
      h3 {
        margin: 0 0 12px 0;
        color: #303133;
        font-size: 16px;
        font-weight: 600;
        padding-bottom: 8px;
        border-bottom: 1px solid #ebeef5;
      }
      
      .tags-container {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        
        .empty-text {
          color: #909399;
          font-size: 14px;
        }
      }
      
      .certifications-container {
        display: flex;
        flex-wrap: wrap;
      }
      
      .introduction-text {
        color: #606266;
        line-height: 1.8;
        white-space: pre-wrap;
        word-break: break-word;
        padding: 12px;
        background: #f5f7fa;
        border-radius: 4px;
      }
    }
  }
}
</style>


